package controllers

import (
	"encoding/json"
	"fmt"
	"gitee.com/angrysnail/youai/backend/models"
	"gitee.com/angrysnail/youai/backend/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type ElderController struct {
	//类似于继承，其内的属性ElderController可以直接用
	beego.Controller
}

// 插入老年人信息
func (c *ElderController) Insert() {
	elder := &models.Elder{}
	err := c.ParseForm(elder)
	if err == nil {
		o := orm.NewOrm()
		//插入后，id自动放入到了elder中
		id, err := o.Insert(elder)
		if err != nil {
			utils.LogError("wrong when insert elder, elderId is %d", id)
			return
		} else if id > 0 {
			utils.LogError("insert successful, elderId is %d", id)
		}
	}
	c.Data["json"] = elder
	c.ServeJSON()
}

func (c *ElderController) AddChildren() {
	elderId, _ := c.GetInt(":id", -1)
	elder, err := models.ElderOne(elderId)
	fmt.Print(elder)
	if err == nil && elder != nil {
		childrenJson := c.Ctx.Input.RequestBody
		var childrend []models.Child
		err = json.Unmarshal(childrenJson, &childrend)
		if err == nil {
			o := orm.NewOrm()
			o.Begin()
			rows, err1 := o.InsertMulti(len(childrend), childrend)
			if err1 == nil && rows >= 1 {
				for _, child := range childrend {
					elderChildMap := make(map[string]int)
					elderChildMap["youai_elder_id"] = elderId
					elderChildMap["youai_child_id"] = child.Id
					o.Insert(elderChildMap)
				}
				c.Data["json"] = "success"
				c.ServeJSON()
				return
			}
			o.Commit()
		}
	}
	c.Data["json"] = "fail"
	return
}

// 查询老年人信息
func (c *ElderController) Get() {
	id, _ := c.GetInt(":id", -1)
	elder, err := models.ElderOne(id)
	if err != nil {
		utils.LogError("error when to query elder, {}", err)
		return
	}
	c.Data["json"] = elder
	c.ServeJSON()
}

// 查询老人的列表
func (c *ElderController) List() {
	name := c.GetString("name")
	male, _ := c.GetBool("male")
	alone, _ := c.GetBool("alone")
	param := &models.ElderQueryparam{}
	param.Name = name
	param.Male = male
	param.Alone = alone
	list, err := models.ElderList(param)
	if err != nil {
		utils.LogError("error when to query elder list, %s", err)
		return
	}
	c.Data["json"] = list
	c.ServeJSON()
}
